﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZ.Common
{
    /// <summary>
    /// 使用时间过期的缓存类封装
    /// </summary>
    /// <typeparam name="Tkey">键的类型</typeparam>
    /// <typeparam name="TValue">值的类型</typeparam>
    public class CacheManager<Tkey, TValue> where TValue : class
    {
        Dictionary<Tkey, TValue> _cachetable = new Dictionary<Tkey, TValue>(1024);
        Dictionary<Tkey, DateTime> _cachetime = new Dictionary<Tkey, DateTime>(1024);
        int _time;
        /// <summary>
        /// 带有更新时间的缓存
        /// </summary>
        /// <param name="cachetime">缓存的时间，单位秒</param>
        public CacheManager(int cachetime)
        {
            _time = cachetime;
        }

        /// <summary>
        /// 获取指定缓存的值，若没有则返回null。
        /// </summary>
        /// <param name="index">键</param>
        /// <returns>值</returns>
        public TValue this[Tkey index]
        {
            get
            {
                if (!_cachetime.ContainsKey(index))
                {
                    return null;
                }

                if (_cachetime[index].AddSeconds(_time) < DateTime.Now)
                {
                    _cachetime.Remove(index);
                    _cachetable.Remove(index);
                    return null;
                }
                return _cachetable[index];
            }
            set
            {
                _cachetable[index] = value;
                _cachetime[index] = DateTime.Now;
            }
        }
    }
}